from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from .forms import CustomUserCreationForm

def register_view(request):
    if request.method == "POST":
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, "注册成功！")
            return redirect("login")  # 注册成功后重定向到登录页面
        messages.error(request, "注册失败，请检查您的输入。")
    else:
        form = CustomUserCreationForm()
    return render(request=request, template_name="users/register.html", context={"form": form})

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.success(request, "登录成功！")
                return redirect('ai_config') # 登录成功后重定向到AI配置页面
            else:
                messages.error(request, "无效的用户名或密码。")
        else:
            messages.error(request, "无效的用户名或密码。")
    else:
        form = AuthenticationForm()
    return render(request=request, template_name="users/login.html", context={"form": form})

def logout_view(request):
    logout(request)
    return redirect("login")
